package com.dao.book;

import com.enitiy.Book;
import com.enitiy.User;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.utils.page.Page;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * 创建作者 ：MySunshine
 * 创建时间 2022/10/28 9:04
 * 项目名称 SHUSHAN
 */
public class BookDaoImpl implements  BookDao{
    QueryRunner qr = new QueryRunner(new ComboPooledDataSource());
    @Override  //查询全部图书
    public List<Book> SelectBookAll(Page p) throws SQLException {
        String sql="select * from book where 1=1";
        if (p.getName()!=null&&!p.getName().equals("")){
            sql+=" and book like'%"+p.getName()+"%'";
        }
        sql+="  limit ?,?";
        int pageSize = p.getPageSize();
        int startIndex= (p.getPageNum()-1)*pageSize;
        return  qr.query(sql,new BeanListHandler<Book>(Book.class),startIndex, pageSize);
    }
    public List<Book> SelectBookAll() throws SQLException {
        String sql="select * from book";
        return qr.query(sql,new BeanListHandler<Book>(Book.class));
    }

    @Override
    public int BookSelectAllNum(Page p) throws SQLException {
        String sql="select count(*) from book where  1=1 ";
        if (p.getName()!=null&&!p.getName().equals("")){
            sql+=" and book like'%"+p.getName()+"%'";
        }
        long count = qr.query(sql, new ScalarHandler<Long>());
        return (int)count;
    }

    @Override //根据id删除图书
    public boolean DeleteBookById(int i) throws SQLException {
        String sql="delete from book where bid=? ";
        int update = qr.update(sql, i);
        return update>=1?true:false;
    }

    @Override//根据id查询图书
    public Book SelectBookById(int i) throws SQLException {
        String sql="select * from book where bid=?";
        return qr.query(sql,new BeanHandler<Book>(Book.class),i);
    }

    @Override//根据id修改图书
    public boolean UpdateBookById(Book b) throws SQLException {
        String sql="update  book set book=?,user=? ,kid=?,synopsis=? where bid=?";
        int update = qr.update(sql, b.getBook(), b.getUser(), b.getKid(), b.getSynopsis(), b.getBid());
        return update>=1?true:false;
    }

    @Override//添加图书
    public boolean AddBook(Book book) throws SQLException {
        String sql="insert into book(book,user,kid,synopsis,img,url) value(?,?,?,?,?,?)";
        int update = qr.update(sql,book.getBook(),book.getUser(),book.getKid(),book.getSynopsis(),book.getImg(),book.getUrl());
        return update>=1?true:false;
    }

    @Override //根据类型查询书籍
    public List<Book> SelectBookByKid(int k) throws SQLException {
        String sql="select * from book where kid=?";
        return     qr.query(sql,new BeanListHandler<Book>(Book.class),k);
    }

}
